import {convertToChinaNum,getmatchshortname} from '../../utils/utils';
const app = getApp()
// pages/newindex/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    sponsorlogoes:'',
    matchinprepare: [ 
       /*{matchinfo:{
        courseinfo: {couresid: "1148", coursename: "贵阳乐湾国际高尔夫俱乐部", courseadress: {}},
        currentround: "1",
        distance: "1938",
        groups:  [],
        isGroup: "1",
        isperson: "1",
        isteam: "0",
        matchRounds: "1",
        matchendDate: "2024-05-15",
        matchid: "4205",
        matchindex: 0,
        matchisreg: 1,
        matchlogo: "",
        matchmsg: "华西赛区",
        matchname: "第一届君品习酒中国高尔夫精英公开赛【贵阳站】",
        matchstartDate: "2024-05-15",
        matchstatus: "比赛未开始",
        matchstatuscode: "N",
        matchsuppend: "0",
        mt_area: "华西赛区",
        mt_type: 0,
        mt_type_msg: "精英赛",
        shortmatchname: "【贵阳站】",
      }
    }, {matchinfo:{
      courseinfo: {couresid: "1148", coursename: "北京华彬庄园高尔夫球会", courseadress: {}},
      currentround: "1",
      distance: "1938",
      groups:  [],
      isGroup: "1",
      isperson: "1",
      isteam: "0",
      matchRounds: "1",
      matchendDate: "2024-05-16",
      matchid: "4205",
      matchindex: 0,
      matchisreg: 1,
      matchlogo: "",
      matchmsg: "华北赛区",
      matchname: "第一届君品习酒中国高尔夫精英公开赛【北京站】",
      matchstartDate: "2024-05-16",
      matchstatus: "比赛未开始",
      matchstatuscode: "N",
      matchsuppend: "0",
      mt_area: "华北赛区",
      mt_type: 0,
      mt_type_msg: "精英赛",
      shortmatchname: "【贵阳站】",
    }
  }*/],


  resliveinfo:[
    /*{
      nickname:'贵阳站',
      startTimestr:'2024-5-6 10:00',
      reservable:true,
      status:0,
    }*/
  ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  ///获取首页滚动照片
  this.getIndexpics();
 this.getSponsors();

     
    ///获取正在进行的比赛信息
    this.getmatchinprogress(false);
    ///获取正在报名的比赛
    this.getmatchinforeg();
   
    this.getindexdata();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 0
    })
    console.log("matchinprepare",this.data.matchinprepare);
  }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

 
   /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      path: '/pages/newindex/index', // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:'/images/thurmb.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容
     
    }
    // 返回shareObj
    return shareObj;
  },

    /**
   * 用户分享朋友圈
   */
  onShareTimeline(){
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      query: 'userID='+ app.globalData.userInfo.userID , // 默认是当前页面，自定义页面路径中携带的参数，如 path?a=1&b=2 的 “?” 后面部分
      imageUrl:'/images/iconlogo.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
     

    };
   
    // 返回shareObj
    return shareObj;
},


//首页数据

getindexdata(){
  var that = this;
   
    
  app.getindexdata("",
    function(res){
        if(res.data.data){
          that.setData({indexdata:res.data.data})
          console.log("getindexdata",that.data.indexdata);
        }
        
    })
  
},

  
  ///获取首页图片
  getIndexpics() {
    var that = this;
   
    
    app.getIndexpics(
      function(res){
          if(res.data.data.news){
            var indexpageUrl= [];
            var thurmbs = res.data.data.news;
            for(var index= 0;index<thurmbs.length;index++)
            {
              indexpageUrl.push(thurmbs[index]);
            }
              that.setData({indexpageUrl:indexpageUrl});
              console.log("that.data.indexpageUrl");
              console.log(that.data.indexpageUrl);
          }
          else{
            console.log("that.data.indexpageUrl:[]");
            that.setData({indexpageUrl:[]});
          }
      })
    

  },

  
  ///获取所有的赞助商列表
  getSponsors: function () {
    var that = this;
    app.getlogoes(function(res){
      if(res.data.data){
     
        console.log("sponsorlogoes",res.data.data);
        that.setData({sponsorlogoes:res.data.data});
        app.globalData.sponsorlogoes = that.data.sponsorlogoes;

        if(res.data.data.ads ){
          app.globalData.bannerAd = res.data.data.ads;
          wx.setStorageSync('AD',  app.globalData.bannerAd);
        }
        else{
          app.globalData.bannerAd ="";
          wx.setStorageSync('AD',  app.globalData.bannerAd);
        }
      }
    
    },0);
   
  },


  geticon(e){
     var index = e.currentTarget.dataset.index;
     if(index == 1){
       wx.navigateTo({
         url: '/pages/News/newlists/index',
       })
     }
     if(index == 2){
      wx.navigateTo({
        url: '/pages/News/photolist/index',
      })
    }

    if(index == 3){
      wx.navigateTo({
        url: '/pages/News/livelists/index',
      })
    }
    if(index == 0){
      wx.navigateTo({
        url: '/pages/Dealer/Dealerlists/index',
      })
    }
  },
  
  //data
  getmatchesdata:function(){
    var that = this;
    app.getmatchesdata("","",function(res){
      console.log("getmatchesdata-res",res);
      if(res.data.data){

        that.setData({tourdata:res.data.data});
      }
      else{
     
        that.setData({tourdata:""});
      }
 },function(){

 }) ;
  },

  getmatchesscoredata:function(){
    var that = this;
    app.getmatchesscoredata("","",function(res){
      console.log("getmatchesscoredata-res",res);
      if(res.data.data){
        var all_scores_max =  res.data.data.all_scores_max;
        all_scores_max.minbmt = getmatchshortname(  all_scores_max.minbmt);
        all_scores_max.mininsmt = getmatchshortname(  all_scores_max.mininsmt);
        all_scores_max.minmt = getmatchshortname(  all_scores_max.minmt);
        all_scores_max.minnetmt = getmatchshortname(  all_scores_max.minnetmt);
        all_scores_max.minouttmt = getmatchshortname(  all_scores_max.minouttmt);
        all_scores_max.diffmt = getmatchshortname(  all_scores_max.diffmt);
        
        that.setData({tourscoredata:all_scores_max});
      }
      else{
     
        that.setData({tourscoredata:""});
      }
 },function(){

 }) ;
 app.getmatchesplayeredata("","",function(res){
  console.log("getmatchesplayeredata-res",res);
  if(res.data.data){
    var all_players_max =  res.data.data.all_players_max;
    all_players_max.fmt = getmatchshortname(  all_players_max.fmt);
    all_players_max.mintmt = getmatchshortname(  all_players_max.mintmt);
    all_players_max.mmt = getmatchshortname(  all_players_max.mmt);
    all_players_max.pmt = getmatchshortname(  all_players_max.pmt);
    that.setData({tourplayersdata:res.data.data.all_players_max});
  }
  else{
 
    that.setData({tourplayersdata:""});
  }
},function(){

}) ;


 
  },

  
  
  ///打开matchcard
  _openmatch: function (e) {
    /*wx.requestSubscribeMessage({
      tmplIds: ['LFT3BEcr7jfe4AtrHealLmgBsYujzpfPNIcC9c1GYR4'],
      success (res) { },
      fail(res){console.log(res)}
    });*/
    console.log(e);
  
    let matchinfo = e.currentTarget.dataset.matchinfo;
    let currenttab = e.currentTarget.dataset.currenttab;

    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/match?currenttab='+currenttab
    })
  },
  
  //获取正在开始比赛的成绩
  getmatchinprogressleaders(matchinfolist, isautorefresh) {
    var that = this;
    var matchleaders  = [];
    
    var currentMatchlists = matchinfolist;
    console.log("getmatchinprogressleaders");
    console.log(currentMatchlists);
    if(!currentMatchlists){
      return;
    }
    
    for(var index = 0; index<currentMatchlists.length;index++ ){
      app.getmatchleadersbyround(currentMatchlists[index].matchid,currentMatchlists[index].currentround, function (res) {
        matchleaders.push(res.data.data);  
        console.log("matchleaders");    
        console.log(matchleaders);        
        that.setData({matchleaders:  matchleaders  });
       // app.globalData.currentMatch = that.data.match;    
      });
    }

   
    

  },

  //获取正在报名的比赛
  getmatchinforeg(isautorefresh) {
    var that = this;
    app.getmatchinforeg(new Date().getFullYear(),"",function (res) {
     console.log("getmatchinforeg");
     console.log(res.data.data.monthmatches);
      if(res.data.data.monthmatches){
        var monthmathes = res.data.data.monthmatches;
        var matchinfo = [];
        for(var index=0;index<monthmathes.length;index++){
            var matches = monthmathes[index].matches;
            for(var matchindex=0;matchindex<matches.length;matchindex++){
            if(matches[matchindex].matchstatuscode=='R'){
              console.log("matches[matchindex]");
              console.log(matches[matchindex]);
              matchinfo.push(matches[matchindex]);
            }
          }
        }
        that.setData({
          matchinforeg: matchinfo
        })
      console.log("getmatchinfo-matchinfo");
      console.log(that.data.matchinforeg);
      }
      else{
        that.setData({
          matchinfo: null
        })
      }
    
  },function () {
    if (!isautorefresh) {
     
      wx.hideLoading();
    }
  });
   
  },
 

  //获取赛事信息
  getmatchinprogress(isautorefresh) {
    
    var that = this;
    if (!isautorefresh) {
     
    wx.showNavigationBarLoading();
  }
  app.getmatchinprogress(new Date().getFullYear(),"",function (res) {
      console.log("getmatchinprogress-res");
      console.log(res);
      if(res.data.data.monthmatches){

        var monthmathes = res.data.data.monthmatches;
        var matchinfo = [];
        for(var index=0;index<monthmathes.length;index++){
            var matches = monthmathes[index].matches;
            if(matches){
              matchinfo = matchinfo.concat(matches);
            }
        }
        that.setData({
          matchinfo: matchinfo
        })
      console.log("getmatchinforeg-matchinfo");
      console.log(that.data.matchinfo);

      ///获取正在进行比赛的成绩
      that.getmatchinprogressleaders(that.data.matchinfo, isautorefresh);
      if(that.data.timer!= ''){
        clearInterval(that.data.timer);
      }
      else
      var timer = setInterval(function() {
        console.log("matchinfo");
        console.log(matchinfo);
        that.getmatchinprogressleaders(matchinfo,true);
        console.log("index:刷新30秒了----------------------------------------------------")
      }, app.globalData.refreshtime);
      that.setData({timer:timer});
    
    }
    else{ 

      that.setData({
        matchinfo: null,
        matchleaders:null
      })
       
    }
    
  },function () {
    if (!isautorefresh) {
     
      wx.hideNavigationBarLoading();
    }
  });
   
    
      


   
  },


   ///打开注册页面
   _openmatchreg(e) {
    let matchinfo = e.detail.matchinfo;
    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/match'
    })

  },


})